package com.iamteer.day23;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

public class TCPClient {

	public static void main(String[] args) {
//		tcpClient();
		chatClient();
	}
	
	public static void tcpClient() {
		try {
			//1. 建立 TCP 服务
			Socket socket = new Socket(InetAddress.getLocalHost(), 9090);
			//2. 获取 Socket 输出流
			OutputStream out = socket.getOutputStream();
			//3. 利用输出流对象把数据写出
			out.write("我是客户端。。。".getBytes());
			InputStream in = socket.getInputStream();
			byte[] buf = new byte[1024];
			int length = -1;
			length = in.read(buf);
			System.out.println(new String(buf, 0, length));
			//4. 关闭资源
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void chatClient() {
		try {
			Socket socket = new Socket(InetAddress.getLocalHost(), 9090);
			OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println("[ " + line + " ]");
				line += "\r\n";		//这里是个大坑！不换行，服务端接收一直不成功
				writer.write(line);
				writer.flush();		//这里也是个大坑！不刷数据发不出去
			}
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

}
